import cursorn.web.RequestScope;
import groovy.lang.Closure;
import play.exceptions.TagInternalException;
import play.exceptions.TemplateExecutionException;
import play.templates.FastTags;
import play.templates.GroovyTemplate;
import play.templates.JavaExtensions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * $author ted
 */
public class MyJavaTags extends FastTags {
    public static void _addJsPaths(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine) {
        List<String> paths = argsToStringOrListOfStrings(args, template, fromLine);

        for(String path : paths) {
            RequestScope.pageDependencies().addJsPath(path.trim());
        }
    }

    public static void _addCssPaths(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine) {
        List<String> paths = argsToStringOrListOfStrings(args, template, fromLine);

        for(String path : paths) {
            RequestScope.pageDependencies().addCssPath(path.trim());
        }
    }

    private static List<String> argsToStringOrListOfStrings(Map<?, ?> args, GroovyTemplate.ExecutableTemplate template, int fromLine) {
        List<String> paths = new ArrayList<String>();
        Object arg = args.get("arg");
        if(arg instanceof List) {
            paths.addAll((List<String>) arg);
        } else if(arg instanceof String) {
            paths.add(arg.toString());
        } else {
            throw new TemplateExecutionException(template.template, fromLine, "Could not convert to String or list of Strings", new TagInternalException("Could not convert to String or list of Strings"));
        }
        return paths;
    }

    public static void _addJsInit(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine) {
        String initJs = JavaExtensions.toString(body);
        RequestScope.pageDependencies().addJsInit(initJs);
    }
}
